﻿#!/usr/bin/env python3
# coding:utf-8
# encoding:utf-8
import psutil
import datetime
import time
import redis
from redis.sentinel import Sentinel
import json
import string
import socket, fcntl, struct
import array


# 当前时间
#now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
#print(now_time)

# # 查看cpu物理个数的信息
# print(u"物理CPU个数: %s" % psutil.cpu_count(logical=False))

# # CPU的使用率
# cpu = (str(psutil.cpu_percent(1))) + '%'
# print(u"cup使用率: %s" % cpu)

# 查看内存信息,剩余内存.free  总共.total
# round()函数方法为返回浮点数x的四舍五入值。

host = '172.16.4.125'
port = 6379
password='123456'

nodes = [('192.168.1.2',26379), ('192.168.1.3',26379), ('192.168.1.4',26379)]
master_name = 'mymaster'
network_name = "bond0"
database = 0

sentinel = Sentinel(nodes, socket_timeout=0.5)
master = sentinel.discover_master(master_name)
sentinel.discover_slaves(master_name)

master = sentinel.master_for(master_name,socket_timeout=0.5,password='111111',db=database)

slave = sentinel.slave_for(master_name,socket_timeout=0.5,password='111111',db=database)

#pool = redis.ConnectionPool(host=host, port=port, password =password, decode_responses=True)
#r = redis.Redis(connection_pool=pool)
#服务数组信息 按照下标，1：端口号，2：服务标识，3：所属服务器，4：服务器ip，5：服务运行状态,6:功能描述，7：启动时间，8运行时长
serverLists = []
			
def get_memory():
	free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))+ "G"
	total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))+ "G"
	memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
	dict = {"total":total, "free":free, "memory":memory,"time":get_time()}
	return dict
	
	
# 系统启动时间
def get_time():
	return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
	#return datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
	
	
def get_cpu():
	cpu=psutil.cpu_percent(1)
	cpu_times = psutil.cpu_times()
	count = psutil.cpu_count(logical=False)
	dict = {"count ":count, "cpu":cpu,"time":get_time()}
	return dict
	
	
# 系统用户
#users_count = len(psutil.users())

#users_list = ",".join([u.name for u in psutil.users()])
#print(u"当前有%s个用户，分别是 %s" % (users_count, users_list))

def get_network():
# 网卡，可以得到网卡属性，连接数，当前流量等信息
	net = psutil.net_io_counters()
	
	bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
	bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
	dict = {"bytesRecv":bytes_rcvd, "bytesSent":bytes_sent}
	return dict
	
	
def disk():
	print('-----------------------------磁盘信息---------------------------------------')	
	io = psutil.disk_partitions()
	#print("系统磁盘信息：" + str(io))
	o = psutil.disk_usage("/")
	total = str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G"
	used = str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G"
	free = str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G"
	persent = o.percent
	dict = {"total":total, "used":used, "free":free, "persent":persent}
	#for i in io:
		#o = psutil.disk_usage("/")
		#print("总容量：" + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
		#print("已用容量：" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
		#print("可用容量：" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")	
	return dict 
	print('-----------------------------进程信息-------------------------------------')

	
def get_local_ip(ifname):

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', bytes(ifname[:15].encode('utf-8'))))
        ret = socket.inet_ntoa(inet[20:24])

        return ret

		
print(get_local_ip(network_name))
#获取主机名
def machine_info():
	host_name = socket.gethostname()
	ip_address = get_local_ip(network_name)
	#get_local_ip(network_name)
	dict = {"host_name":host_name, "ip_address":ip_address}
	return dict 
	
	
# 查看系统全部进程
def processInfo():
	sz = {}
	for pnum in psutil.pids():
		port_pid(pnum)
	
	
def port_pid(pid):
	p = ''
	try: 
		p = psutil.Process(pid)
	except:
		return
	data = p.connections()
	data_listen = [x for x in data if 'LISTEN' in x]
	for i in range(0, len(serverLists)):
		for port in data_listen:
			if serverLists[i].get("port")==port.laddr[1]:
				serverLists[i]["pid"] = p.pid,
				serverLists[i]["name"] = p.name()
				serverLists[i]["status"] = 1
				serverLists[i]["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S",  time.localtime(p.create_time()))
				serverLists[i]["runTime"] = str(round((time.time()-p.create_time())/3600,2))+"小时"
				break
						
	
	
if __name__ == '__main__': 
	ip = get_local_ip(network_name)
	while 1:
		serverLists = [{"port":80,"name":"","serverflag":"nginx","machine":"仿真服务器A","ip":ip,"status":0,"description":"发布文件服务和前端服务","createTime":"","runTime":""},
				{"port":54321,"name":"","serverflag":"kingbase","machine":"仿真服务器A","ip":ip,"status":0,"description":"人大进仓数据库服务","createTime":"","runTime":""},
				{"port":6379,"name":"","serverflag":"redis","machine":"仿真服务器A","ip":ip,"status":0,"description":"redis内存数据库","createTime":"","runTime":""},
				{"port":8888,"name":"","serverflag":"java","machine":"仿真服务器A","ip":ip,"status":0,"description":"java后端服务","createTime":"","runTime":""}]
		array = {}
		processInfo()
		#array['process'] = processInfo()
		array['machine_info'] =machine_info()
		array['disk'] = disk()
		array['cpu'] =  get_cpu()
		array['time'] = get_time()
		array['memory'] = get_memory()
		key =get_local_ip(network_name)+ 'monitor' + get_time()
		softkey = "soft"+get_local_ip(network_name)+ 'monitor' + get_time()
		print('----redis存储-----'+key)
		master.set(key, json.dumps(array), ex=3600)
		a = json.dumps(serverLists, ensure_ascii=False)
		#print(a)
		master.set(softkey, a, ex=3600)
		time.sleep(20)
